#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2011/02/20

@author: Administrator
'''

from django.utils import simplejson
from google.appengine.api import users
from google.appengine.ext import db
import datetime
import time

class GaeEncoder(simplejson.JSONEncoder):
    def default(self, obj): 
        if hasattr(obj, '__json__'): 
            return getattr(obj, '__json__')() 
       
        # db.Query に対応
        if isinstance(obj, db.Query):
            return list(obj)

        if isinstance(obj, db.GqlQuery): 
            return list(obj) 
        
        elif isinstance(obj, db.Model): 
            properties = obj.properties().items() 
            output = {} 
            for field, value in properties: 
                output[field] = getattr(obj, field)
            return output 
        
        # datetime は単純な文字列にする
        elif isinstance(obj, datetime.datetime): 
            return str(obj)
        
        elif isinstance(obj, datetime.date): 
            return str(obj)
        
        elif isinstance(obj, time.struct_time):
            return list(obj)

        elif isinstance(obj, users.User):
            output = {}
            methods = ['nickname', 'email', 'auth_domain']
            for method in methods:
                output[method] = getattr(obj, method)()
            return output
        
        return simplejson.JSONEncoder.default(self, obj) 

def encode(obj):
    return GaeEncoder().encode(obj)